package org.example.c4;

import lombok.extern.slf4j.Slf4j;

import java.util.concurrent.atomic.AtomicReference;

/**
 * ABA问题
 * AtomicReference实现了线程安全，但无法解决ＡＢＡ问题
 */

@Slf4j
public class Demo2 {
    static AtomicReference<String> str;

    public static void main(String[] args) {
        str = new AtomicReference<>("A");
        final String old = str.get();

        doOther();

        log.info("A -> C {}", str.compareAndSet(old, "c"));
    }

    private static void doOther() {
        final Thread t1 = new Thread(() -> {
            String old = str.get();
            log.info("{} -> B {}", old, str.compareAndSet(old, "B"));

            old = str.get();
            log.info("{} -> A {}", old, str.compareAndSet(old, "A"));
        }, "t1");

        t1.start();
        try {
            t1.join();
        } catch (InterruptedException e) {
        }
    }
}
